<!--课程与题库-分类题库-->
<template>
  <div class="question-bank-container">
    <el-row :gutter="20">
      <!-- 左侧题库菜单 -->
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>题库列表</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              @click="showAddBankDialog"
            >
              + 创建题库
            </el-button>
          </div>
          <!--@select返回选中菜单下index-->
          <el-menu :default-active="activeBankId" @select="handleBankSelect">
            <el-menu-item v-for="bank in questionBanks" :key="bank.id" :index="bank.id">
              <div class="bank-item">
                <div class="bank-info">
                  <h4>{{ bank.name }}</h4>
                  <p>{{ bank.major }} | {{ bank.level }}</p>
                </div>
                <div class="bank-actions">
                  <el-button
                    size="mini"
                    type="text"
                    @click.stop="editBank(bank.id)"
                  >编辑
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    @click.stop="deleteBank(bank.id)"
                  >删除
                  </el-button>
                </div>
              </div>
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>

      <!-- 右侧题目管理区域 ，当currentBank不为空，就显示右边菜单-->
      <el-col :span="18">
        <el-card class="box-card" v-if="currentBank">
          <div slot="header" class="clearfix">
            <span>题目管理 - {{ currentBank.name }}</span>
            <div style="float: right;">
              <el-button-group>
                <el-button
                  size="small"
                  @click="showImportDialog"
                >导入题目
                </el-button>
                <el-button
                  size="small"
                  @click="exportQuestions"
                >导出题目
                </el-button>
                <el-button
                  size="small"
                  type="primary"
                  @click="showAddQuestionDialog"
                >+ 添加题目
                </el-button>
              </el-button-group>
            </div>
          </div>

          <!-- 题目类型筛选 -->
          <div class="question-filter">
            <el-radio-group v-model="currentQuestionType" @change="filterQuestions">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button :label="0">单选题</el-radio-button>
              <el-radio-button :label="1">多选题</el-radio-button>
              <el-radio-button :label="2">判断题</el-radio-button>
              <el-radio-button :label="3">简答题</el-radio-button>
            </el-radio-group>
            <el-button
              style="float: right"
              size="small"
              type="danger"
              :disabled="selectedQuestions.length === 0"
              @click="batchDeleteQuestions"
            >
              批量删除 ({{ selectedQuestions.length }})
            </el-button>
          </div>

          <!-- 题目表格,展现题目内容-->
          <el-table
            :data="filteredQuestions"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              width="55"
            ></el-table-column>
            <el-table-column prop="type" label="题目" width="120">
              <!-- single-单选；multiple-多选；judge-判断；short-简答             -->
              <!--              <template v-slot="scope">{{ getQuestionTypeText(scope.row.type) }}</template>-->
              <template v-slot="scope">{{ getQuestionTypeText(scope.row.baseinfo.btktm_type) }}</template>
            </el-table-column>
            <!--            <el-table-column  prop="content"  label="题干" ></el-table-column>-->
            <el-table-column prop="baseinfo.btktm_name" label="题干" width="650"></el-table-column>
            <el-table-column label="选项" width="200"
                             v-if="currentQuestionType !== 'judge' && currentQuestionType !== 'short'"
            >
              <template v-slot="scope">
                <!--                {{ scope.row.options ? scope.row.options.length : 0 }}-->
                {{ scope.row.items ? scope.row.items.length : 0 }}
              </template>
            </el-table-column>
            <el-table-column label="正确答案" width="300" v-if="currentQuestionType !== 'short'">
              <template v-slot="scope">
                <span v-if="scope.row.baseinfo.btktm_type === 2">
<!--                  {{ scope.row.answer ? '正确' : '错误' }}-->
                  {{ scope.row.answers[0].btktma_name }}
                </span>
                <span v-else-if="scope.row.items">
                  <!--处理成ABCD-->
                  {{ getCorrectAnswers(scope.row) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="170"
            >
              <template v-slot="scope">
                <el-button
                  size="mini"
                  @click="editQuestion(scope.row)"
                >编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="deleteQuestion(scope.row.baseinfo.btktm_code)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination">
            <span>共 {{ totalQuestions }} 条</span>
            <el-select
              v-model="pageSize"
              @change="handleSizeChange"
              style="width: 100px; margin: 0 10px;"
            >
              <el-option
                v-for="size in [10, 20, 30, 50]"
                :key="size"
                :label="`${size}条/页`"
                :value="size"
              ></el-option>
            </el-select>
            <el-pagination
              :current-page="currentPage"
              :page-size="pageSize"
              :total="totalQuestions"
              layout="prev, pager, next, jumper"
              @current-change="handlePageChange"
            ></el-pagination>
          </div>
        </el-card>

        <!-- 题库添加/编辑对话框 -->
        <el-dialog
          :title="bankDialogTitle"
          :visible.sync="bankDialogVisible"
          :close-on-click-modal = false
          width="40%"
        >
          <el-form :model="currentBankForm" label-width="100px">
            <el-form-item label="题库名称" prop="name">
              <el-input v-model="currentBankForm.name"></el-input>
            </el-form-item>
            <el-form-item label="所属专业" prop="major">
              <el-select
                v-model="currentBankForm.major"
                placeholder="请选择专业"
                style="width: 100%"
              >
                <el-option
                  v-for="major in majors"
                  :key="major"
                  :label="major"
                  :value="major"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="考试等级" prop="level">
              <el-select
                v-model="currentBankForm.level"
                placeholder="请选择等级"
                style="width: 100%"
              >
                <el-option
                  v-for="level in levels"
                  :key="level"
                  :label="level"
                  :value="level"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 题库描述 -->
            <el-form-item label="题库描述：" prop="user_phoneno">
              <el-input
                v-model="currentBankForm.description"
                placeholder="请输入描述"
                clearable
                type="textarea"
                rows="10"
              ></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="bankDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveBank">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 题目添加/编辑对话框 -->
        <el-dialog
          :title="questionDialogTitle"
          :visible.sync="questionDialogVisible"
          :close-on-click-modal = false
          width="60%"
        >
          <el-form :model="currentQuestionForm" label-width="100px">
            <el-form-item label="题目类型" prop="type">
              <el-select
                v-model="currentQuestionForm.type"
                @change="handleQuestionTypeChange"
                style="width: 100%"
              >
                <el-option label="单选题" value="single"></el-option>
                <el-option label="多选题" value="multiple"></el-option>
                <el-option label="判断题" value="judge"></el-option>
                <el-option label="简答题" value="short"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="题干" prop="content">
              <el-input
                type="textarea"
                :rows="3"
                v-model="currentQuestionForm.content"
              ></el-input>
            </el-form-item>

            <!-- 选项部分 -->
            <div v-if="currentQuestionForm.type !== 'judge' && currentQuestionForm.type !== 'short'">
              <el-form-item label="题目选项">
                <div
                  v-for="(option, index) in currentQuestionForm.options"
                  :key="index"
                  class="option-item"
                >
                  <el-checkbox
                    v-model="option.isCorrect"

                  >
                    {{ String.fromCharCode(65 + index) }}.
                  </el-checkbox>
<!--单选有选项时不可用    :disabled="currentQuestionForm.type === 'single' && hasSingleCorrectAnswer"-->
                  <el-input
                    v-model="option.text"
                    style="width: 80%; margin-left: 10px;"
                  ></el-input>
                  <el-button
                    type="text"
                    @click="removeOption(index)"
                    v-if="currentQuestionForm.options.length > 2"
                  >
                    <i class="el-icon-delete"></i>
                  </el-button>
                </div>
                <el-button
                  type="text"
                  @click="addOption"
                  v-if="currentQuestionForm.options.length < 6"
                >
                  + 添加选项
                </el-button>
              </el-form-item>
            </div>

            <!-- 判断题答案 -->
            <el-form-item
              label="正确答案"
              v-if="currentQuestionForm.type === 'judge'"
            >
              <el-radio-group v-model="currentQuestionForm.answer">
                <el-radio :label="true">正确</el-radio>
                <el-radio :label="false">错误</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 简答题答案 -->
            <el-form-item
              label="参考答案"
              v-if="currentQuestionForm.type === 'short'"
            >
              <el-input
                type="textarea"
                :rows="3"
                v-model="currentQuestionForm.answer"
              ></el-input>
            </el-form-item>
            <!-- 答案解析 -->
            <el-form-item
              label="答案解析"
            >
              <el-input
                type="textarea"
                :rows="3"
                v-model="currentQuestionForm.answerdesc"
              ></el-input>
            </el-form-item>
            <!--            <el-form-item label="难度">-->
            <!--              <el-rate-->
            <!--                v-model="currentQuestionForm.difficulty"-->
            <!--                :max="5"-->
            <!--              ></el-rate>-->
            <!--            </el-form-item>-->
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="questionDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveQuestion">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 导入题目对话框 -->
        <el-dialog
          title="导入题目"
          :visible.sync="importDialogVisible"
          width="50%"
        >
          <el-upload
            class="upload-demo"
            action="#"
            :on-change="handleFileChange"
            :on-success="handleImportSuccess"
            :before-upload="beforeUpload"
            :file-list="fileList"
            accept=".doc,.docx"
            drag
            :auto-upload="false"

          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将docx文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传doc/docx文件</div>
          </el-upload>
          <div class="download-template">
            <!--            <el-button type="text" @click="downloadTemplate">下载导入模板</el-button>-->
            <el-link type="primary" :href="downDocx" target="_blank">下载导入模板</el-link>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="importDialogVisible = false">取 消</el-button>
          </span>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  createbtk,
  querybtklist,
  createbtkitems,
  querybtkitems,
  querybtkdetail,
  deletebtkitems, deletebtk, updatebtk, fileuploadres, importbtk, querydict, updatebtkitems
} from "../../api/InstitutionApi";
import {formatDate} from "../../utils/util";
import * as XLSX from "xlsx";
import {saveAs} from 'file-saver'

export default {
  data() {
    return {
      // 下载模板
      downDocx: 'https://www.xzbky.com/static/kangyangtrain/1000/timudemo.docx',
      // 题库相关数据
      questionBanks: [
        {
          id: '1',
          name: '计算机基础题库',
          major: '计算机科学',
          level: '初级',
          description: '',
          questions: []
        },
        {
          id: '2',
          name: '医学常识题库',
          major: '医学',
          level: '中级',
          description: '',
          questions: []
        },
        {
          id: '3',
          name: '法律知识题库',
          major: '法律',
          level: '高级',
          description: '',
          questions: []
        }
      ],
      activeBankId: '1',
      // 当前题库
      currentBank: null,
      // 题库数组
      currentBankForm: {
        id: '',
        name: '',
        major: '',
        level: '',
        description: ''
      },
      bankDialogVisible: false,
      bankDialogTitle: '创建题库',
      isEditingBank: false,
      majors: ['计算机科学', '医学', '法律', '经济学', '工程学'],
      levels: ['初级', '中级', '高级', '专家级'],

      // 题目相关数据（单选、多选、判断、简答）
      currentQuestionType: 'all',
      // 右边展现时最终的数组（过滤处理后的）
      filteredQuestions: [],
      selectedQuestions: [],
      currentQuestionForm: this.getDefaultQuestion(),
      questionDialogVisible: false, ////题目添加框
      questionEditvisible: false, ////题目编辑框
      questionDialogTitle: '添加题目',
      isEditingQuestion: false,
      editQuestionId: null,
      chanageFormItem: {}, ////传递上传的转换的结构

      // 导入导出
      importDialogVisible: false,
      fileList: [],
      exportAllQ: [], ////导出时存储所有数据

      // 字典项
      dictNode: [], ///字典根项
      tmpItem: {},  //临时存储ITEM项
      returnItem: [], ////临时存储返回项
      suozhuanye: [],//所属专业
      kaoshilevel: [], ///考试等级


      // 分页
      currentPage: 1, ///当前页码
      pageSize: 10,  ///每页几行
      totalQuestions: 0  ///总记录数
    };
  },
  computed: {
    hasSingleCorrectAnswer() {
      // 选项中为true个数大于1
      return this.currentQuestionForm.options.filter(opt => opt.isCorrect).length >= 1;
    }
  },
  created() {
    // 获取题库列表
    this.getTkList()
    // 初始化数据，主要为每个题库添加对应的题型
    // this.initSampleQuestions();
    //默认选中第一个题库，并展现题库中的题目
    setTimeout(() => {
      // currentBank未过滤条件时存储的题库与题目内容
      this.currentBank = this.questionBanks.find(b => b.id === this.activeBankId);
      console.log('显示当前题库：', this.currentBank)
      // 根据当前选中的题库，获取接口的所有题目
      this.getbtKitems()
      // 按上面的过滤条件进行过滤显示题目类型
      setTimeout(() => {
        this.filterQuestions();
      }, 800)
      //   加载字典项
      // 获取字典根项
      this.selectdictNode()
    }, 800)
  },
  methods: {
    // 查询所有题库列表
    getTkList() {
      querybtklist().then(res => {
        this.questionBanks = []
        console.log('获取所有题库列表：', res)
        let base_info = res.data.base_info;
        this.activeBankId = base_info[0].btk_code
        for (let i = 0; i < base_info.length; i++) {
          let currentTk = {}
          currentTk.id = base_info[i].btk_code;
          currentTk.name = base_info[i].btk_name;
          currentTk.major = base_info[i].btk_zy;
          currentTk.level = base_info[i].btk_zylevel;
          currentTk.description = base_info[i].btk_desc;
          currentTk.tol = base_info[i].tol;
          currentTk.isbuy = base_info[i].isbuy;
          currentTk.questions = [];
          this.questionBanks.push(currentTk);
        }
      })
    },
    // 查询题库的题目项内容
    getbtKitems() {
      querybtkdetail({
        "btktmcode": this.activeBankId,
        "pageindex": this.currentPage,
        "pagesize": this.pageSize
      }).then(res => {
        let base_info = res.data.data.base_info
        console.log('读取回来的题目：', res, base_info, this.currentPage, this.pageSize);
        this.currentBank.questions = []
        this.currentBank.questions = base_info
        this.totalQuestions = res.data.data.tolcount
        console.log('将题库内容题目获取后：', this.currentBank,this.totalQuestions)
      })
    },

    // 查询字典开始
    selectdictNode() {
      querydict({
        "dictcode": "0"
      }).then(res => {
        console.log('根项字典', res)
        this.dictNode = []
        this.dictNode = res.data.data.base_info
        this.selectItem()
      })
    },
    // 查询字典项
    async selectItem() {
      this.majors = []
      this.levels = []
      // 所属专业
      this.tmpItem = {}
      this.tmpItem = this.dictNode.filter(item => item.dict_name === '所属专业')
      let returnItemjobName = []
      returnItemjobName = await this.selectItemApi(this.tmpItem[0].dict_code)

      for (let i = 0; i < returnItemjobName.length; i++) {
        this.majors.push(returnItemjobName[i].dict_name)
      }

      // 考试等级
      this.tmpItem = {}
      this.tmpItem = this.dictNode.filter(item => item.dict_name === '考试等级')
      let returnItemjobClassfiy = []
      returnItemjobClassfiy = await this.selectItemApi(this.tmpItem[0].dict_code)
      for (let i = 0; i < returnItemjobClassfiy.length; i++) {
        this.levels.push(returnItemjobClassfiy[i].dict_name)
      }
      console.log('tmpItem-1:', this.suozhuanye, this.kaoshilevel);
    },

    selectItemApi(itemcode) {
      return querydict({
        "dictcode": itemcode
      }).then(res => res.data.data.base_info)
    },
    // 查询字典结束

    // 初始化示例题目数据
    initSampleQuestions() {
      // 每个题库添加题目，遍历添加，questionBanks题库数组
      this.questionBanks.forEach(bank => {
        bank.questions = [
          {
            id: this.generateId(),
            type: 'single',
            content: 'Vue.js的作者是谁？',
            options: [
              {text: 'Evan You', isCorrect: true},
              {text: '尤雨溪', isCorrect: false},
              {text: 'John Doe', isCorrect: false},
              {text: 'Jane Smith', isCorrect: false}
            ],
            bankId: bank.id
          },
          {
            id: this.generateId(),
            type: 'multiple',
            content: '下列哪些是Vue的特性？',
            options: [
              {text: '响应式数据', isCorrect: true},
              {text: '组件化', isCorrect: true},
              {text: '双向数据绑定', isCorrect: true},
              {text: '虚拟DOM', isCorrect: false}
            ],
            bankId: bank.id
          },
          {
            id: this.generateId(),
            type: 'judge',
            content: 'Vue是基于React开发的。',
            answer: false,
            // difficulty: 1,
            bankId: bank.id
          },
          {
            id: this.generateId(),
            type: 'short',
            content: '简述Vue的生命周期钩子函数。',
            answer: 'beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeDestroy, destroyed',
            // difficulty: 4,
            bankId: bank.id
          }
        ];
      });
    },

    // 题库上传开始
    // 当文件变化时
    async handleFileChange(file, fileList) {
      // 1.当文件变化时，需要首先将临时文件与文件名称存储入相应的数组对象中
      // 获取文件的临时路径（不同浏览器兼容处理）
      const tempPath = file.url || URL.createObjectURL(file.raw);
      // // 调用存储函数
      // const newVideo = {
      //   name: file.name,
      //   url: tempPath
      // };
      let formData = new FormData();
      // const fileupdown = this.fileList[0].raw; // 获取原始文件对象
      const fileupdown = file.raw
      // 文件形式上传
      formData.append('btkcode', this.activeBankId); // 要导入的题库code
      formData.append('resfile', fileupdown); //文件docx文档,
      console.log('当前文件列表:', formData, this.activeBankId, fileupdown);
      // 以文件形式上传视频到服务端
      this.fileuploadres(formData);

    },

    // 以文件形式上传题库文件
    fileuploadres(formData, newVideo) {
      // 显示加载中
      const loading = this.$loading({
        lock: true,
        text: '题库上传中 0%', // 初始文本
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      importbtk(formData, {
        headers: {
          'Content-Type': 'multipart/form-data' // 必须设置
        },
        onUploadProgress: (progressEvent) => {
          // 上传进度显示
          const percent = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          loading.setText(`题库上传中 ${percent}%`);
        }
      }).then(res => {
        // 上传成功
        loading.close();
        this.$message.success('题库上传成功');
        console.log('tiku:', res)
        // 获取题库列表
        // this.getTkList()
        // 根据当前选中的题库，获取接口的所有题目
        // this.getbtKitems()
        // 根据当前选择的题库重新加载
        this.handleBankSelect(this.activeBankId)
        this.getbtKitems()

        // let resCode = res.data.res_code;
        // this.$set(newVideo, 'videocode', resCode);
        // 2.向id为chapterid的项目添加视频路径与文件名
        // this.addVideoUrlToChapter(chapterid, newVideo);
      })
    },
    // 题库上传结束

    // 题库操作方法
    showAddBankDialog() {
      this.currentBankForm = {
        id: '',
        name: '',
        major: '',
        level: '',
        description: ''
      };
      this.bankDialogTitle = '创建题库';
      this.isEditingBank = false;
      this.bankDialogVisible = true;
    },
    // 编辑题库打开编辑框
    editBank(bankId) {
      const bank = this.questionBanks.find(b => b.id === bankId);
      this.currentBankForm = {...bank};
      this.bankDialogTitle = '编辑题库';
      this.isEditingBank = true;
      this.bankDialogVisible = true;
    },
    // 删除题库
    deleteBank(bankId) {
      this.$confirm('确定删除该题库吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // console.log('deleteTM:', bankId)
        // const index = this.questionBanks.findIndex(b => b.id === bankId);
        // this.questionBanks.splice(index, 1);
        // this.$message.success('删除成功');
        // if (this.activeBankId === bankId && this.questionBanks.length > 0) {
        //   this.activeBankId = this.questionBanks[0].id;
        //   this.currentBank = this.questionBanks[0];
        //   this.filterQuestions();
        // }
        deletebtk({
          "btkcode": bankId
        }).then(res => {
          console.log('删除题库：', res)
          this.getTkList()

        })

      });
    },
    // 题库的添加/编辑框保存
    saveBank() {
      if (!this.currentBankForm.name || !this.currentBankForm.major || !this.currentBankForm.level) {
        this.$message.error('请填写完整信息');
        return;
      }
      // isEditingBank是否编辑标识
      if (this.isEditingBank) {
        // 编辑题库
        // console.log('编辑中：', this.currentBankForm)
        // const index = this.questionBanks.findIndex(b => b.id === this.currentBankForm.id);
        // this.questionBanks.splice(index, 1, { ...this.currentBankForm });
        // this.$message.success('更新成功');
        updatebtk({
          "btkcode": this.currentBankForm.id,//#题库code
          "btkname": this.currentBankForm.name,//#题库名称
          "btkzy": this.currentBankForm.major,//#题库专业
          "btkzylevel": this.currentBankForm.level,//#题库级别
          "btkdesc": this.currentBankForm.description,//#题库描述
        }).then(res => {
          console.log('编辑题库-1：', res)
          this.getTkList()
        })
      } else {
        // 添加题库
        createbtk({
          "btkname": this.currentBankForm.name, //#题库名称
          "btkzy": this.currentBankForm.major, //#题库专业
          "btkzylevel": this.currentBankForm.level, //#题库级别
          "btkdesc": this.currentBankForm.description, //#题库描述
        }).then(res => {
          console.log('添加题库：', res)
          // 刷新题库
          this.getTkList()
        })
        // const newId = this.generateId();
        // this.questionBanks.push({
        //   ...this.currentBankForm,
        //   id: newId,
        //   questions: []
        // });
        // this.$message.success('添加成功');
      }
      this.bankDialogVisible = false;
    },
    // 当前选择的题库
    handleBankSelect(bankId) {
      // 初始化分页
      this.currentPage = 1
      this.pageSize = 10
      console.log('点击题库当前项bankId：', bankId)
      // 当activeBankId不为空，就显示右边菜单
      this.activeBankId = bankId;
      this.currentBank = this.questionBanks.find(b => b.id === bankId);
      // 根据当前选中的题库，获取接口的所有题目
      this.getbtKitems()
      // 按上面的过滤条件进行过滤显示题目类型
      setTimeout(() => {
        // 过滤条件
        this.filterQuestions();
      }, 1000)
    },

    // 题目操作方法
    getDefaultQuestion() {
      return {
        id: '',
        type: 'single',
        content: '',
        options: [
          {text: '', isCorrect: false},
          {text: '', isCorrect: false},
          {text: '', isCorrect: false},
          {text: '', isCorrect: false}
        ],
        answer: '',
        answerdesc: '',
        bankId: this.activeBankId   ///题库ID
      };
      // return {
      //   content: '',
      //   type: 'single',
      //   options: [],
      //   answer: [],
      //   anserDesc: '',
      //   difficulty: 3,
      //   bankId: this.activeBankId  ///当前选择的题库的ID
      // };
    },
    // 类型转处理
    changeType(type) {
      // 转换题型为文字
      // 0单选，1多选，2判断，3简答
      switch (type) {
        case 0:
          this.chanageFormItem.btktmtype = 'single';
          break;
        case 1:
          this.chanageFormItem.btktmtype = 'multiple';
          break;
        case 2:
          this.chanageFormItem.btktmtype = 'judge';
          break;
        case 3:
          this.chanageFormItem.btktmtype = 'short';
          break;
      }
      return this.chanageFormItem.btktmtype
    },

    // 转换成编辑框需要的结构
    apiToQuestion(apiData) {
      console.log('API转本地前：', apiData)
      this.currentQuestionForm.id = apiData.baseinfo.btktm_code
      this.currentQuestionForm.type = this.changeType(apiData.baseinfo.btktm_type)
      this.currentQuestionForm.content = apiData.baseinfo.btktm_name
      this.currentQuestionForm.answer = apiData.answers.btktma_name
      this.currentQuestionForm.answerdesc = apiData.baseinfo.btktm_answerdesc
      this.currentQuestionForm.bankId = this.activeBankId
      this.currentQuestionForm.options = []
      // 编辑时处理单选和多选题
      if (apiData.baseinfo.btktm_type === 0 || apiData.baseinfo.btktm_type === 1) {
        for (let i = 0; i < apiData.items.length; i++) {
          for (let j = 0; j < apiData.answers.length; j++) {
            if (apiData.items[i].btktmi_name === apiData.answers[j].btktma_name) {
              this.currentQuestionForm.options.push({
                text: apiData.items[i].btktmi_name,
                isCorrect: true
              })
              break;
            } else {
              this.currentQuestionForm.options.push({
                text: apiData.items[i].btktmi_name,
                isCorrect: false
              })
              break;
            }
          }
        }
      } else if (apiData.baseinfo.btktm_type === 2) {
        if (apiData.answers[0].btktma_name === '正确') {
          this.currentQuestionForm.answer = true
        } else {
          this.currentQuestionForm.answer = false
        }
      } else {
        this.currentQuestionForm.answer = apiData.answers[0].btktma_name
      }

      console.log('API转本地后：', this.currentQuestionForm)
    },

    // 添加题目
    showAddQuestionDialog() {
      if (this.activeBankId == '1') {
        this.$message.error('请先选择题库');
        return;
      }
      this.currentQuestionForm = this.getDefaultQuestion();
      this.questionDialogTitle = '添加题目';
      // 是否编辑题目
      this.isEditingQuestion = false;
      this.questionDialogVisible = true;
    },
    // 编辑题目
    editQuestion(question) {
      // 转换成编辑框需要的结构
      this.apiToQuestion(question)
      // this.currentQuestionForm = JSON.parse(JSON.stringify(question));

      this.questionDialogTitle = '编辑题目';
      this.questionDialogVisible = true;
      // 获取并保存要编辑的题目CODE
      // this.editQuestionId = question.id;
      this.editQuestionId = question.baseinfo.btktm_code;
      // console.log('编辑',question,this.editQuestionId);
      // 编辑题目开关
      this.isEditingQuestion = true;
      // this.questionEditvisible = true;
    },
    // 删除考题的某一个题目项或多个题目项
    deleteQuestion(questionId) {
      this.$confirm('确定删除该题目吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 比对当前题库ID与总题库ID，并过滤出题库
        // const bank = this.questionBanks.find(b => b.id === this.activeBankId);
        // // 取得题目的索引index
        // // const index = bank.questions.findIndex(q => q.id === questionId);
        // const index = bank.questions.findIndex(q => q.baseinfo.btktm_code === questionId);
        // console.log('del:',bank,questionId,index)
        // bank.questions.splice(index, 1);
        // this.filterQuestions();
        // this.$message.success('删除成功');
        // 通过接口删除题目,参数必须是数组
        let deleteData = []
        deleteData.push(questionId)
        this.btktmDelete(deleteData);
      });
    },
    // 批量删除
    batchDeleteQuestions() {
      this.$confirm(`确定删除选中的 ${this.selectedQuestions.length} 道题目吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // console.log('double:', this.selectedQuestions)
        // const bank = this.questionBanks.find(b => b.id === this.activeBankId);
        // this.selectedQuestions.forEach(question => {
        //   const index = bank.questions.findIndex(q => q.id === question.id);
        //   if (index !== -1) {
        //     bank.questions.splice(index, 1);
        //   }
        // });
        // this.selectedQuestions = [];
        // this.filterQuestions();
        // this.$message.success('批量删除成功');
        let deleteDate = []
        for (let i = 0; i < this.selectedQuestions.length; i++) {
          deleteDate.push(this.selectedQuestions[i].baseinfo.btktm_code);
        }
        this.btktmDelete(deleteDate);
      });
    },
    // 删除接口处理
    btktmDelete(deleteData) {
      deletebtkitems({
        "btktmcode": deleteData
      }).then(res => {
        // console.log('delete:',res)
        this.handleBankSelect(this.activeBankId)
      })
    },
    // 保存题目
    saveQuestion() {
      if (this.activeBankId === '1') {
        this.$message.error('请先选择题库');
        return;
      }

      if (!this.currentQuestionForm.content) {
        this.$message.error('请填写题目内容');
        return;
      }

      if (this.currentQuestionForm.type !== 'judge' && this.currentQuestionForm.type !== 'short') {
        const hasContent = this.currentQuestionForm.options.every(opt => opt.text.trim());
        if (!hasContent) {
          this.$message.error('请填写所有选项内容');
          return;
        }

        const hasCorrect = this.currentQuestionForm.options.some(opt => opt.isCorrect);
        if (!hasCorrect) {
          this.$message.error('请至少选择一个正确答案');
          return;
        }
      }

      const bank = this.questionBanks.find(b => b.id === this.activeBankId);

      // 转换结构
      this.chanageForm()
      console.log('保存转换的题目：', this.chanageFormItem, this.currentQuestionForm)

      if (this.isEditingQuestion) {
        updatebtkitems({
          "btktmcode": this.editQuestionId, //#题库选项code
          "btktmname": this.chanageFormItem.btktname,//#题目名称
          "btktmtype": this.chanageFormItem.btktmtype,//#题目类型
          "btktmanswerdesc": this.chanageFormItem.btktmanswerdesc,//#答案描述
          "btktmitems": this.chanageFormItem.btktmitems,//#题目选项["AAA","BBB","CCC"]
          "btktmansweritems":this.chanageFormItem.btktmansweritems,//#题目答案选项数组，['A','B','C']
        }).then(res => {
          console.log('eidt:', res)
          this.handleBankSelect(this.activeBankId)

        })
        const index = bank.questions.findIndex(q => q.id === this.editQuestionId);
        bank.questions.splice(index, 1, {...this.currentQuestionForm});
        this.$message.success('更新成功');
      } else {
        // 添加题目
        // bank.questions.push({
        //   ...this.currentQuestionForm,
        //   id: this.generateId()
        // });


        // 传接口
        createbtkitems({
          "btkcode": this.chanageFormItem.btkcode, //#题库code
          "btktmname": this.chanageFormItem.btktname, ///#题目名称
          "btktmtype": this.chanageFormItem.btktmtype, ///#题目类型
          "btktmanswerdesc": this.chanageFormItem.btktmanswerdesc,  ///#答案描述
          "btktmitems": this.chanageFormItem.btktmitems, ///#题目选项["AAA","BBB","CCC"]
          "btktmansweritems": this.chanageFormItem.btktmansweritems,  ///#题目答案选项数组，['A','B','C']
        }).then(res => {
          console.log('题目保存结果：', res, this.currentBank)
          this.handleBankSelect(this.activeBankId)

        })

        this.$message.success('添加成功');
      }
      this.questionDialogVisible = false;
      // 过滤条件
      this.filterQuestions();
    },
    // 转成可以上传的数据结构
    chanageForm() {
      this.chanageFormItem = []
      // this.chanageFormItem
      this.chanageFormItem.btkcode = this.currentQuestionForm.bankId
      this.chanageFormItem.btktname = this.currentQuestionForm.content
      // 转换题型为文字
      // 0单选，1多选，2判断，3简答
      switch (this.currentQuestionForm.type) {
        case 'single':
          this.chanageFormItem.btktmtype = '0';
          break;
        case 'multiple':
          this.chanageFormItem.btktmtype = '1';
          break;
        case 'judge':
          this.chanageFormItem.btktmtype = '2';
          break;
        case 'short':
          this.chanageFormItem.btktmtype = '3';
          break;
      }
      this.chanageFormItem.btktmanswerdesc = this.currentQuestionForm.answerdesc;
      this.chanageFormItem.btktmitems = []
      this.chanageFormItem.btktmansweritems = []
      //  转换题目与答案转成选项内容
      if (this.currentQuestionForm.type === 'judge') {
        console.log('编辑题库-2：', this.chanageFormItem)
        if (this.currentQuestionForm.answer) {
          this.chanageFormItem.btktmansweritems.push('正确')
        } else {
          this.chanageFormItem.btktmansweritems.push('错误')
        }
      } else if (this.currentQuestionForm.type === 'short') {
        this.chanageFormItem.btktmansweritems.push(this.currentQuestionForm.answer)
      } else {
        //单选与多选
        for (var i = 0; i < this.currentQuestionForm.options.length; i++) {
          this.chanageFormItem.btktmitems.push(this.currentQuestionForm.options[i].text)
          if (this.currentQuestionForm.options[i].isCorrect) {
            this.chanageFormItem.btktmansweritems.push(this.currentQuestionForm.options[i].text)
          }
        }
      }

    },
    handleQuestionTypeChange(type) {
      if (type === 'judge' || type === 'short') {
        this.currentQuestionForm.options = [];
      } else {
        if (this.currentQuestionForm.options.length < 2) {
          this.currentQuestionForm.options = [
            {text: '', isCorrect: false},
            {text: '', isCorrect: false},
            {text: '', isCorrect: false},
            {text: '', isCorrect: false}
          ];
        }
      }
    },
    addOption() {
      if (this.currentQuestionForm.options.length < 6) {
        this.currentQuestionForm.options.push({text: '', isCorrect: false});
      }
    },
    removeOption(index) {
      if (this.currentQuestionForm.options.length > 2) {
        this.currentQuestionForm.options.splice(index, 1);
      }
    },
    handleOptionCheck(index) {
      if (this.currentQuestionForm.type === 'single') {
        this.currentQuestionForm.options.forEach((opt, i) => {
          if (i !== index) opt.isCorrect = false;
        });
      }
    },
    getQuestionTypeText(type) {
      const types = {
        "0": '单选题',
        "1": '多选题',
        "2": '判断题',
        "3": '简答题'
      };
      // 表示若左为false，则返回右值
      return types[type] || type;
    },
    // 生成正确答案
    getCorrectAnswers(question) {
      // if (question.type === 'single' || question.type === 'multiple') {
      //   // // 假设 question 是一个对象，包含 options 数组
      //   return question.options
      //     // 筛选出正确答案（isCorrect为true的选项）
      //     .filter(opt => opt.isCorrect)
      //     // 将筛选后的选项按顺序转换为字母（A=65, B=66... Unicode编码）
      //     .map((opt, index) => String.fromCharCode(65 + index))
      //   // 将字母数组拼接成字符串（如 "A, C"）
      //     .join(', ');
      // }
      if (question.baseinfo.btktm_type === 0 || question.baseinfo.btktm_type === 1) {
        console.log('答案-2：', question)
        // // 假设 question 是一个对象，包含 options 数组
        // let anser = question.items
        //   // 筛选出正确答案（isCorrect为true的选项）
        //   .filter(opt => opt.btktmi_name === question.answers.btktma_name)
        //   // 将筛选后的选项按顺序转换为字母（A=65, B=66... Unicode编码）
        //   .map((opt, index) => String.fromCharCode(65 + index))
        //   // 将字母数组拼接成字符串（如 "A, C"）
        //   .join(', ');
        // 判断选择项与答案相等，并转为ABCD，逗号分隔
        let anwserCode = [];
        for (var i = 0; i < question.items.length; i++) {
          for (var j = 0; j < question.answers.length; j++) {
            if (question.items[i].btktmi_name == question.answers[j].btktma_name) {
              anwserCode.push(String.fromCharCode(65 + i));
            }
          }
        }
        return anwserCode.join(',');
      }
      return '';
    },
    // 根据过滤最终输入的内容
    filterQuestions() {
      // 若题库为空，则直接返回
      if (!this.currentBank) return;
      if (this.currentQuestionType === 'all') {
        // 数组浅拷贝
        this.filteredQuestions = [...this.currentBank.questions];
      } else {
        this.filteredQuestions = this.currentBank.questions.filter(
          // q => q.type === this.currentQuestionType
          q => q.baseinfo.btktm_type === this.currentQuestionType
        );
      }
      // 初始化分页
      // this.currentPage = 1
      // this.pageSize = 10
      // this.totalQuestions = this.filteredQuestions.length
      console.log('过滤后需要展现的内容', this.filteredQuestions, this.currentQuestionType);
      // this.totalQuestions = this.filteredQuestions.length;
      // this.handlePageChange(1);
    },
    handleSelectionChange(selection) {
      this.selectedQuestions = selection;
      console.log('选择中项：', this.selectedQuestions);
    },

    // 导入导出方法
    showImportDialog() {
      this.importDialogVisible = true;
    },

    beforeUpload(file) {
      const allowedTypes = [
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        '.docx'
      ];
      return allowedTypes.includes(file.raw.type) || file.name.endsWith('.docx');

      // const isExcel = file.type === 'application/vnd.ms-excel' ||
      //   file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      // if (!isExcel) {
      //   this.$message.error('只能上传docx文件!');
      // }
      // return isExcel;
    },
    handleImportSuccess(response, file, fileList) {
      if (response.success) {
        const bank = this.questionBanks.find(b => b.id === this.activeBankId);
        bank.questions = [...bank.questions, ...response.data];
        this.filterQuestions();
        this.importDialogVisible = false;
        this.$message.success('导入成功');
      } else {
        this.$message.error(response.message || '导入失败');
      }
    },

    // 导出文件
    exportQuestions() {
      // 实际项目中这里应该调用API导出Excel
      // this.$message.success('导出功能将在实际项目中实现');
      // 当点击导出时,重新获取接口的所有数据
      this.exportAllQuestions()
      setTimeout(() => {
        //自定义导出
        let nowDataTime = formatDate(new Date())
        console.log('日期时间:', nowDataTime)
        const header = ['题目', '题干', '选项', '正确答案']
        // console.log('导出',this.this.exportAllQ)
        const body = this.exportAllQ.map(r => [r.baseinfo.btktm_type === 0 ? "单选题" : r.baseinfo.btktm_type === 1 ? "多选题" : r.baseinfo.btktm_type === 2 ? "判断题" : "简答题", r.baseinfo.btktm_name, r.items.length, r.baseinfo.btktm_type === 0 || r.baseinfo.btktm_type === 1 ? this.getCorrectAnswers(r) : r.answers[0].btktma_name
        ])
        const ws = XLSX.utils.aoa_to_sheet([header, ...body])
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
        const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'array'})
        saveAs(new Blob([wbout], {type: 'application/octet-stream'}), '题目数据' + nowDataTime + '.xlsx')
      }, 1000)
    },
    exportAllQuestions() {
      // 导出时调用接口
      querybtkdetail({
        "btktmcode": this.activeBankId,
        "pageindex": 1,
        "pagesize": this.totalQuestions
      }).then(res => {
        let base_info = res.data.data.base_info
        console.log('导出返回的数据：', res, base_info, this.currentPage, this.pageSize);
        this.exportAllQ = []
        this.exportAllQ = base_info
        console.log('导出返回的数据-1：', this.currentBank)
      })
    },

    // 生成答案
    chanageAnswer(type, answer) {
      if (type === 0 || type === 1) {
        console.log('答案-2：', question)
        let anwserCode = [];
        for (var i = 0; i < answer.items.length; i++) {
          for (var j = 0; j < answer.answers.length; j++) {
            if (question.items[i].btktmi_name == question.answers[j].btktma_name) {
              anwserCode.push(String.fromCharCode(65 + i));
            }
          }
        }
        return anwserCode.join(',');
      }
      return '';

    },
    downloadTemplate() {
      // 实际项目中这里应该提供模板下载
      this.$message.success('模板下载功能将在实际项目中实现');
    },

    // 分页方法
    handleSizeChange(size) {
      console.log('当前页:', size, this.currentPage);
      // 默认第1页,默认每页显示10条
      this.pageSize = size;
      this.handlePageChange(1);
    },
    handlePageChange(page) {
      console.log('当前页:', this.pageSize, this.currentPage + 1);
      this.currentPage = page;
      // this.handleBankSelect()
      this.getbtKitems()
      // 按上面的过滤条件进行过滤显示题目类型
      setTimeout(() => {
        this.filterQuestions();
      }, 800)
      // this.filterQuestions()
      // 实际项目中这里应该调用API分页获取数据
      // 这里简单模拟分页效果
      // const start = (page - 1) * this.pageSize;
      // const end = start + this.pageSize;
      // this.filteredQuestions = this.filteredQuestions.slice(start, end);
    },

    // 生成随机ID
    generateId() {
      return Math.floor(Math.random() * 100000000).toString();
    }
  }
};
</script>

<style scoped>
.question-bank-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
  height: calc(100vh - 100px);
  overflow-y: auto;
}

.bank-item {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.bank-info {
  flex: 1;
}

.bank-info h4 {
  margin: 0;
  font-size: 14px;
}

.bank-info p {
  margin: 5px 0 0;
  font-size: 12px;
  color: #909399;
}

.bank-actions {
  margin-left: 10px;
}

.question-filter {
  margin-bottom: 20px;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20px;
}

.upload-demo {
  text-align: center;
}

.download-template {
  text-align: center;
  margin-top: 20px;
}

.el-menu {
  border-right: none;
}

.el-menu-item {
  height: auto;
  line-height: normal;
  padding: 10px 20px;
}
</style>

